﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;

namespace Client.System
{
    public class Audio
    {
        Dictionary<String, SoundEffect> soundEffects;
        private Dictionary<String,SoundEffectInstance> currentlyPlayingAudio;


        public void LoadAudio(ContentManager content)
        {
            soundEffects = new Dictionary<String, SoundEffect>
                               {{"PongBG", content.Load<SoundEffect>(@"Audio\mario_bg_converted")},
                                {"Bounce"  , content.Load<SoundEffect>(@"Audio\smb_1-up")}
                               };
            currentlyPlayingAudio = new Dictionary<string, SoundEffectInstance>();
            //var sf =  content.Load<SoundEffect>("");
        }

        public void Play(String soundName , bool isLooping )
        {
            CleanUp();
            //if already playing 'soundName' then return immediatly
            if (currentlyPlayingAudio.Keys.Contains(soundName))
                return;


            var s = soundEffects[soundName].CreateInstance();
            s.IsLooped = isLooping;
            //s.Volume = Static.PlayerProfile.GameSetting.BGVolume;
            currentlyPlayingAudio.Add(soundName, s);
            s.Play();


            
        }
        /// <summary>
        /// removes all the sounds that have stopped.
        /// </summary>
        private void CleanUp()
        {
            var tmp = new Dictionary<String,SoundEffectInstance>(currentlyPlayingAudio);

            foreach (var soundEffectInstance in tmp)
            {
                if (soundEffectInstance.Value.State == SoundState.Stopped)
                {
                    currentlyPlayingAudio.Remove(soundEffectInstance.Key);
                }
            }
        }

        /// <summary>
        /// stops all playing music
        /// </summary>
        public void Reset()
        {
            foreach (var i in currentlyPlayingAudio)
            {
                i.Value.Stop();
            }
            currentlyPlayingAudio.Clear();
        }

    }
}
